<?php

namespace Portal\Domain;

class Menu
{
    /**
     *
     * @param mixed $where
     * @return array
     */
    public function menus($where = [])
    {

        $roleMenuDomain = new RoleMenu();
        $notorm = \Portal\Model\Menu::notorm()->select('id,parent_id AS parentId,name,type,route_name AS routeName,route_path AS routePath,component,sort,visible,icon,redirect,perm')->order('sort');
        if (\PhalApi\DI()->admin->isRoot() == false) {
            $roleIds = \PhalApi\DI()->admin->getRoleIds();
            if (!empty($roleIds)) {
                $menuIds = $roleMenuDomain->getMenuIds($roleIds);
                if (is_array($menuIds) && !empty($menuIds)) {
                    $where['id'] = $menuIds;
                }
            }

        }
        if (!empty($where)) {
            $menus = $notorm->where($where)->fetchPairs('id');
        } else {
            //没有查询条件
            $menus = $notorm->fetchPairs('id');
        }
        $formatMenus = $this->getChildMenus(0, $menus);
        return $formatMenus;
    }

    public function routes()
    {

        if (\PhalApi\DI()->admin->isRoot() == false) {
            //获取用户角色列表
            $roleIds = \PhalApi\DI()->admin->getRoleIds();
            if (empty($roleIds)) {

                return [(object)[]];
            }
            # 获取角色对应的菜单ID列表
            $menuIdDatas = \Portal\Model\RoleMenu::notorm()->select('menu_id')->where(['role_id' => $roleIds])->fetchAll();
            if (empty($menuIdDatas)) {

                return [(object)[]];
            }
            $menuIds = [];
            foreach ($menuIdDatas as $menuIdData) {
                $menuIds[] = $menuIdData['menu_id'];
            }
            $where['id'] = $menuIds;
        }
        //只查询目录，菜单，外链
        $where['type'] = [1,2,3];
        $menus = \Portal\Model\Menu::notorm()->select('route_path AS path,route_path AS name,component,redirect,name AS title,icon,visible,always_show AS alwaysShow,params,id,parent_id AS parentId')->where($where)->order('sort,id')->fetchAll();
        //格式化数据
        $formatMenus = $this->formatRoutesData($menus);

        $menusChilds = $this->getChildMenus(0, $formatMenus);
        return $menusChilds;
    }

    private function formatRoutesData($datas)
    {
        foreach ($datas as $key => $data) {
            /*
                   meta: {
            title: "系统管理",
            icon: "system",
            hidden: false,
            alwaysShow: false,
            params: null,
          },*/
            $meta['title'] = $data['title'];
            $meta['icon'] = $data['icon'];
            $meta['hidden'] = !boolval($data['visible']);
            $meta['alwaysShow'] = boolval($data['alwaysShow']);
            if ($data['params']) {
                $meta['params'] = json_decode($data['params']);
            } else {
                $meta['params'] = null;
            }
            $data['meta'] = $meta;
            $data['name'] = strval($data['name']);
            $data['path'] = strval($data['path']);
            //删除组装的数据
            unset($data['title'],$data['icon'],$data['visible'],$data['alwaysShow'],$data['params']);
            $datas[$key] = $data;
        }

        return $datas;
    }
    //获取树等级
    public function getTreePath($parentId, &$treeArray = [])
    {
        $parentId = intval($parentId);
        // 在数组左边插入元素
        array_unshift($treeArray, $parentId);
        if (intval($parentId) > 0) {
            //获取上级父id
            $getParentData = \Portal\Model\Menu::notorm()->select('parent_id')->where(['id' => $parentId])->fetchOne();
            if (is_array($getParentData) && !empty($getParentData)) {
                $parentId = intval($getParentData['parent_id']);
                // array_unshift($treeArray, $parentId);
                $this->getTreePath($parentId, $treeArray);
            }
        }
        return  $treeArray;
    }

    private function getChildMenus($parentId, $allMenus)
    {
        $childMenus = [];

        foreach ($allMenus as $menu) {
            if ($menu['parentId'] == $parentId) {
                $id = $menu['id'];
                // unset($menu['parentId'],$menu['id']);
                $children = $this->getChildMenus($id, $allMenus);
                // if (!empty($children)) {
                $menu['children'] = $children;
                // }
                $childMenus[] = $menu;

            }
        }
        return $childMenus;
    }

    public function getMenuPerm()
    {
        $returnData = [];
        if (\PhalApi\DI()->admin->isRoot()) {
            $permDatas = \Portal\Model\Menu::notorm()->select('perm')->where('perm <> ?', '')->fetchAll();
        } else {
            $roleMenuDomain = new \Portal\Domain\RoleMenu();
            $roleIds = \PhalApi\DI()->admin->getRoleIds();
            if (!empty($roleIds)) {
                $menuIds = $roleMenuDomain->getMenuIds($roleIds);
                if (is_array($menuIds) && !empty($menuIds)) {
                    //查询menu数据
                    $permDatas = \Portal\Model\Menu::notorm()->select('perm')->where(['id' => $menuIds])->where('perm <> ?', '')->fetchAll();
                }
            }
        }
        if (is_array($permDatas) && !empty($permDatas)) {
            foreach ($permDatas as $permData) {
                $returnData[] = $permData['perm'];
            }
        }
        return $returnData;
    }

    public function getOptions($onlyParent)
    {
        $notorm = \Portal\Model\Menu::notorm();
        if ($onlyParent) {
            $menus = $notorm->select('id,id AS value,parent_id AS parentId,name AS label')->where('type', [1,2])->order('sort,id')->fetchAll();
        } else {
            $menus = $notorm->select('id,id AS value,parent_id AS parentId,name AS label')->fetchAll();
        }
        foreach ($menus as $key => $menu) {
            $menu['value'] = strval($menu['value']);
            $menus[$key] = $menu;
        }
        $menusChilds = $this->getChildMenus(0, $menus);
        return $menusChilds;
    }
    public function getChildren($id, &$childArray = [])
    {
        $currentChildArr = [];
        $getChildDatas = \Portal\Model\Menu::notorm()->select('id')->where(['parent_id' => $id])->fetchAll();
        if (is_array($getChildDatas) && !empty($getChildDatas)) {
            foreach ($getChildDatas as $getChildData) {
                $currentChildArr[] = $getChildData['id'];
                $childArray[] = $getChildData['id'];
            }
            //递归处理
            foreach ($currentChildArr as $currentId) {
                $this->getChildren($currentId, $childArray);
            }
        }

        return  $childArray;
    }
}
